package com.sakura.哈希表;

public class Code202_快乐数 {


    // 快慢指针，如果快指针追上慢指针，则说明有环（永远无法到1），返回false
    // 这题可以理解成 环形链表
    public boolean isHappy(int n) {
        int slow = n;
        int fast = getNext(n);
        while (fast != 1 && fast != slow) {
            slow = getNext(slow);
            fast = getNext(getNext(fast));
        }
        return fast == 1;
    }

    public int getNext(int n ) {
        int totalSum = 0;
        while (n > 0) {
            int d = n % 10;
            n = n / 10;
            totalSum += d * d;
        }
        return totalSum;
    }
}
